// pages/details/details.js
const db = wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    good_all_detail:{},
    num:1,
    cart:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function (options) {
    var that = this
    console.log("首页选择物体传递过来的id",options.id)
    var good_id = options.id - 1
    db.collection('good_all_detail')
    .get()
    .then(res=>{
      console.log(res.data[0].good_all_detail[good_id])
      that.setData({
        good_detail:res.data[0].good_all_detail[good_id]
      })
    })
  },

  changeTc:function(e){
    var tc = e.detail.value;
    var id = this.data.id
    console.log(id)
    console.log(e)
    console.log("changeTc--> tc:",tc)
    this.setData({
       "good_detail.tc": tc
    })
  },

  addToCart: function () {
    wx.getStorage({
      key: 'cart',
      success: res => {
        let isexist = false
        for (var i in res.data) {
          if (this.data.good_detail.id == res.data[i].id){
              isexist = true
              res.data[i].total += this.data.num
          } 
        }
        if (!isexist) {
          let cartitem = this.data.good_detail
          cartitem['total'] = this.data.num
          res.data.push(this.data.good_detail) 
        }
        wx.setStorage({
          data: res.data,
          key: 'cart',
        })
      },
      fail: err => {
        let cartitem = this.data.good_detail
        cartitem['total'] = this.data.num
        let cart = []
        cart.push(cartitem)
        wx.setStorage({
          data: cart,
          key: 'cart',
        })
      }
    })
    wx.showToast({
      title: '加入成功',
      icon:'success',
      mask:true,
    })
    
},

lookToCart: function(){
   wx.switchTab({
     url: '/pages/shopping/shopping',
   })
},



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})